package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.BankCardParams;
import com.baidu.ocr.sdk.model.BankCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SMCardActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_BANKCARD = 111;
    private static final int REQUEST_CODE_GENERAL = 105;

    private TextView djsm1,xiugai1,xiugai2;
    private EditText Card_Home,Card_Id,Card_Home_Phone;
    private ImageView imageView,imageViewimg,smcardfh;
    private Button cardBtn;
    private String user_id,user_name,Idnumber_id;

    private int x=0;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wz_activity_smcard);
        //获取文字识别
        Token();
        getUser_id();

        xiugai1 = findViewById(R.id.cardxiugai1);
        xiugai2 = findViewById(R.id.cardxiugai2);
        djsm1 = findViewById(R.id.carddjsmsm1);

        Card_Home = findViewById(R.id.Card_Home);
        Card_Id = findViewById(R.id.Card_Id);
        Card_Home_Phone = findViewById(R.id.Card_Home_phone);

        imageViewimg = findViewById(R.id.smcardimg);
        imageView = findViewById(R.id.cardsmzm);

        cardBtn = findViewById(R.id.cardBtn);


        xiugai1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(xiugai1.getText().equals("修改")) {
                    //弹出键盘
                    showSoftInputFromWindow(SMCardActivity.this,Card_Home);
                    //设置控件为不可编辑
                    Card_Id.setFocusable(false);
                    xiugai1.setText("确定");
                    xiugai2.setText("修改");
                }else{
                    InputMethodManager imm = (InputMethodManager) SMCardActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(Card_Home.getWindowToken(), 0);
                    Card_Home.setFocusable(false);
                    xiugai1.setText("修改");
                }
            }
        });
        xiugai2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(xiugai2.getText().equals("修改")) {
                    //弹出键盘
                    showSoftInputFromWindow(SMCardActivity.this,Card_Id);
                    //设置控件为不可编辑
                    Card_Home.setFocusable(false);
                    xiugai1.setText("修改");
                    xiugai2.setText("确定");
                }else{
                    InputMethodManager imm = (InputMethodManager) SMCardActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(Card_Id.getWindowToken(), 0);
                    Card_Id.setFocusable(false);
                    xiugai2.setText("修改");
                }
            }
        });
        //点击调用相机隐藏图片文字
        imageViewimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                x=0;
                // 生成intent对象
                Intent intent = new Intent(SMCardActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                startActivityForResult(intent, REQUEST_CODE_BANKCARD);
                //当控件再次被点击时清空图片
                imageViewimg.setImageDrawable(null);
                //显示扫描图标
                imageView.setVisibility(imageView.VISIBLE);
                djsm1.setVisibility(djsm1.VISIBLE);

            }
        });

        //给下一步按钮设置点击事件
        cardBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (x == 0 || Card_Home.getText().toString().trim().equals("") || Card_Id.getText().toString().trim().equals("") || Card_Home_Phone.getText().toString().trim().equals("")) {
                    showToast(SMCardActivity.this, "请完善信息");
                } else {

                    Intent intent = getIntent();
                    user_name = intent.getStringExtra("Idnumber_name");
                    Idnumber_id = intent.getStringExtra("Idnumber_id");

                    String str2 = Card_Id.getText().toString().replaceAll(" ", "");
                    OKManager.getInstance().type1001(user_id, user_name, Idnumber_id, str2, Card_Home_Phone.getText().toString(), new OKManager.func4() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                if (!jsonObject.get("code").toString().trim().equals("0")) {
                                    showToast(SMCardActivity.this, jsonObject.get("message").toString());
                                } else {
                                    Bitmap image = ((BitmapDrawable) imageViewimg.getDrawable()).getBitmap();
                                    sendImage(image);
                                    Intent intent1 = new Intent(SMCardActivity.this, FaceActivity.class);
                                    intent1.putExtra("Idnumber_name", user_name);
                                    intent1.putExtra("Idnumber_id", Idnumber_id);
                                    startActivity(intent1);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String string) {
                            showToast(SMCardActivity.this, "失败");
                        }
                    });


                }
            }
        });

        smcardfh = findViewById(R.id.smcardfh);
        smcardfh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            // 获取调用参数
            String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
            // 通过临时文件获取拍摄的图片
            String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
            //图片转String用于保存
            url = filePath;
            // 判断拍摄类型（通用，身份证，银行卡等）
            BankCardParams param = new BankCardParams();
            param.setImageFile(new File(filePath));
// 调用银行卡识别服务
            OCR.getInstance().recognizeBankCard(param, new OnResultListener<BankCardResult>() {
                @Override
                public void onResult(BankCardResult result) {
                    //收起键盘
//                InputMethodManager imm = (InputMethodManager) SMCardActivity.this
//                        .getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(Card_Home.getWindowToken(), 0);
                    //加载图片
                    imageViewimg.setImageURI(Uri.parse(url));
                    //隐藏扫描图标
                    imageView.setVisibility(imageView.GONE);
                    //隐藏扫描文本
                    djsm1.setVisibility(djsm1.GONE);
                    // 调用成功，返回BankCardResult对象
                    Card_Home.setText(result.getBankName());
                    Card_Id.setText(result.getBankCardNumber());
                    x=1;
                }
                @Override
                public void onError(OCRError error) {
                    // 调用失败，返回OCRError对象
                    showToast(SMCardActivity.this,error+"");
                }
            });
        }

    }
    /**
     * 上传图片到服务器
     *
     * @param bitmap
     */
    private void sendImage(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/CardImg");
        if (!file.exists())
            file.mkdirs();
        File imgFile = new File(file.getAbsolutePath() + "/headimg1.jpeg");
        if (imgFile.exists())
            imgFile.delete();
        try {
            FileOutputStream outputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();

            OKManager.getInstance().type1028(user_id,imgFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        InputMethodManager imm = (InputMethodManager) getSystemService(activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //获取ocr支持
    public void Token(){
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
                showToast(SMCardActivity.this,"网络错误");
            }
        }, getApplicationContext(), "7outqMHRUg9Fjsd3RFs0PZNG", "AIbOlma4wGOchToB6bfUs3Ac41GpB6Wh");
    }



    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    public void getUser_id(){
        //获取用户id
        Object user_info = Preferences.getParam(SMCardActivity.this, "user_info", "");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());

            //账号
            user_id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
